Why does type conversion for [] and !![] return not the same result?
console.log([] == false); // true
console.log(!![] == false); // false
For the first output: https://262.ecma-international.org/5.1/#sec-11.9.3
[] == false is evaluated as ToPrimitive([]) == ToNumber(false) which is ToNumber([]) == ToNumber(false) and finally 0 == 0.
The conversion chain step by step:
We're starting with [] == false.
Step 1:
- If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
Now, we have [] == 0.
Step 2:
- If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
Some examples of this conversion chain:
console.log(Number([]));
console.log(Number(false));
console.log([0] == false);
console.log(['0'] == false);
console.log([1] == true);
console.log(['1'] == true);
console.log(['0'] == 0);
console.log([1] == '1');
console.log([1,2,3] == '1,2,3');
For the second output: an array (even empty) is truthy. ![] returns false. !false returns true.
Some examples:
console.log(Boolean([]));
console.log(![]);
console.log(!![]);